package sk.openit.xml.jaxp.sax;

import java.io.File;
import java.io.IOException;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.SAXParseException;
import org.xml.sax.helpers.DefaultHandler;

public class DbConfigReaderEchoOnly extends DefaultHandler {
	private String fileName;
	
	public DbConfigReaderEchoOnly(String fileName) {
		this.fileName = fileName;
	}
	
	public void process() {
		SAXParserFactory factory = SAXParserFactory.newInstance();
		factory.setValidating(true);
		try {
			SAXParser saxParser = factory.newSAXParser();
			saxParser.parse(new File(fileName), this);
		} catch (ParserConfigurationException e) {
			System.err.println("Wrong SAXParser configuration");			
			e.printStackTrace();
		} catch (SAXException e) {
			System.err.println("Unable to parse XML structure: " + fileName);
			e.printStackTrace();
		} catch (IOException e) {
			System.err.println("Unable to open xml file: " + fileName);
			e.printStackTrace();
		}		
	}

	@Override
	public void startDocument() throws SAXException {
		System.out.println("Start processing XML document");
	}

	@Override
	public void endDocument() throws SAXException {
		System.out.println("Finished processing XML document");
	}

	@Override
	public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
		String text = String.format(" uri=%s, localName=%s, qName=%s, attributes=%s", uri, localName, qName, attributes);
		System.out.println(text);
	}

	@Override
	public void endElement(String uri, String localName, String qName) throws SAXException {
		String text = String.format(" uri=%s, localName=%s, qName=%s", uri, localName, qName);
		System.out.println(text);
	}

	@Override
	public void characters(char[] ch, int start, int length) throws SAXException {		
		String text = String.format("  data=%s", new String(ch, start, length));
		System.out.println(text);
	}
	
	@Override
	public void warning(SAXParseException e) throws SAXException {
		System.err.println("! warning: " + e.getMessage());
	}

	@Override
	public void error(SAXParseException e) throws SAXException {
		System.err.println("!! error: " + e.getMessage());
	}

	@Override
	public void fatalError(SAXParseException e) throws SAXException {
		System.err.println("!!! fatalError: " + e.getMessage());
	}	
}
